<?php
class SubscribeGroupAction extends UserAction{
	
	public function index(){
		
		$model = M('subscribe_group');
		$where['token'] = session('token');
		
		$count = $model->where($where)->count();
		$page = new Page($count,10);
		$models = $model->where($where)->limit($page->firstRow.','.$page->listRows)->select();
		
		$this->assign('models', $models);
		$this->assign('page',$page->show());
		
		$this->display();
	}
	
	public function update(){
		$info = '更新完成，请稍候';
		$flag = true;
		load('@.SubscribeHelper');
		try {
			//$flag = WechatAdvanceAPI::SaveGroupInfo(session('token'));
			SaveGroupInfo(session('token'));
		} catch (Exception $e) {
			Log::write('更新关注者错误：'.$e->getMessage(), Log::WARN);
			$flag = false;
		}
		
		if(!$flag){
			$info = '更新失败，你可以去微信后台查看具体信息';
		}
		
		$this->success($info, U(MODULE_NAME.'/index'));
	}
	
	/**
	 * 更新用户分组信息
	 */
	public function updateMember(){
		$info = '更新完成，请稍候';
		$flag = true;
		load('@.SubscribeHelper');
		try {
			//$flag = WechatAdvanceAPI::SaveGroupInfo(session('token'));
			SaveGroupInfo(session('token'));
			if($flag){
				$model = M('subscriber');
				$where['token'] = session('token');
				$where['issubscribe'] = 1;
				$users = $model->where($where)->select();
				
				foreach ($users as $user){
					$groupinfo = WechatAdvanceAPI::GetUserGroup($user['openid']);
					
					if(isset($groupinfo->groupid)){
						$user['groupid'] = $groupinfo->groupid;
						$model->save($user);
					}
				}
			}
		} catch (Exception $e) {
			Log::write('更新用户所在分组错误：'.$e->getMessage(), Log::WARN);
			$flag = false;
		}
		
		if(!$flag){
			$info = '更新失败，你可以去微信后台查看具体信息';
		}
		$this->success($info, U(MODULE_NAME.'/index'));
	}
	
	public function add(){
		$this->display();
	}

	public function addGroup(){
		$groupName = $_POST['gname'];
		$wxresult = WechatAdvanceAPI::CreateGroup(urlencode($groupName));
		
		if(isset($wxresult->group)){
			$gp = $wxresult->group;
			
			$data ['token'] = session('token');
			$data ['groupid'] = $gp->id;
			$data ['groupname'] = $gp->name;
			$data ['groupcount'] = 0;
			
			M('subscribe_group')->add($data);
			
			$this->success('操作成功',U(MODULE_NAME.'/index'));
		}else{
			Log::write('创建分组失败'.$wxresult, Log::WARN);
			$this->error('操作失败，请检查你的信息',U(MODULE_NAME.'/index'));
		}
	}
	
	public function edit(){
		$groupId = $_REQUEST['id'];
		
		$where['token'] = session('token');
		$where['groupid'] = $groupId;
		$data = M('subscribe_group')->where($where)->find();
		
		if($data){
			$this->assign('gpid', $data['groupid']);
			$this->assign('gpname',$data['groupname']);
			
			$this->display();
		}else{
			$this->error('无效的操作',U(MODULE_NAME.'/index'));
		}
	}
	
	public function editGroup(){
		$groupName = $_POST['gname'];
		$groupId = $_POST['gpid'];
		
		$wxresult = WechatAdvanceAPI::UpdateGroupName($groupId, urlencode($groupName));
		
		if($wxresult->errcode == 0){
			
			$where['token'] = session('token');
			$where['groupid'] = $groupId;
			$data ['groupname'] = $groupName;
			M('subscribe_group')->where($where)->save($data);
			
			$this->success('操作成功',U(MODULE_NAME.'/index'));
		}
		else{
			Log::write('修改分组失败'.$wxresult, Log::WARN);
			$this->error('操作失败，请检查你的信息',U(MODULE_NAME.'/index'));
		}
	}
	
	public function subscriberindex(){
		$where['token'] = session('token');
		$gpinfos = M('subscribe_group')->where($where)->select();
		
		$gidselect = $_POST['gpselect'];
		//筛选分组
		$sqlwhere = '';
		if(isset($gidselect)){
			$where['groupid'] = $gidselect;
			//$sqlwhere = ' WHERE s.groupid='.$gidselect;
			$this->assign('selectid', $gidselect);
		}else{
			$this->assign('selectid', '-100');
		}
		
		
		$where['issubscribe'] = 1;
		
		$subscriber = M('subscriber');
		
		$count=$subscriber->where($where)->count();
		$page=new Page($count,10);
		$subscribers=$subscriber->where($where)->limit($page->firstRow.','.$page->listRows)->select();
		
		foreach ($gpinfos as $key=>$val){
			$g[$val['groupid']] = $val['groupname'];
		}
		
		$this->assign('gpinfos', $gpinfos);
		$this->assign('g', $g);
		$this->assign('subscribers', $subscribers);
		$this->assign('page',$page->show());
		
		
		/* $where['issubscribe'] = 1;
		$subscriber = M('subscriber');
		
		$count=$subscriber->where($where)->count();
		$page=new Page($count,10);
		
		$Model = new Model();
		$sql = 'SELECT s.openid, s.nickname, s.sex, s.city, s.province, s.headimgurl, s.addtime, g.groupname, s.groupid, s.token FROM ai9me_subscriber AS s LEFT JOIN ai9me_subscribe_group AS g ON s.token = g.token AND s.groupid = g.groupid'.$sqlwhere.' limit '.$page->firstRow.','.$page->listRows;
		$voList = $Model->query($sql);
		
		
		$this->assign('gpinfos', $gpinfos);
		$this->assign('subscribers', $voList);
		$this->assign('page',$page->show()); */
		
		$this->display();
	}
	
	public function editMemberGroup(){
		$openid = $_REQUEST['id'];
		$where['token'] = session('token');
		
		$gpinfos = M('subscribe_group')->where($where)->select();
		
		$where['openid'] = $openid;
		$subscriber = M('subscriber')->where($where)->find();
		
		$this->assign('subscriber', $subscriber);
		$this->assign('gpinfos', $gpinfos);
		
		$this->assign('selectid', $subscriber['groupid']);
		
		$this->display();
	} 
	
	public function editSubscribeGroup(){
		$openid = $_POST['openid'];
		$gidselect = $_POST['gpselect'];
		
		if(!isset($gidselect) || !isset($openid)){
			$this->error('错误的请求',U(MODULE_NAME.'/subscriberindex'));
			return;
		}
		
		$wxresult = WechatAdvanceAPI::UpdateUserGroup($openid, $gidselect);
		
		if($wxresult->errcode == 0){
				
			$where['token'] = session('token');
			$where['openid'] = $openid;
			
			$data ['groupid'] = $gidselect;
			
			M('subscriber')->where($where)->save($data);
				
			$this->success('操作成功',U(MODULE_NAME.'/subscriberindex'));
		}
		else{
			Log::write('editSubscribeGroup失败'.$wxresult, Log::WARN);
			$this->error('操作失败，请检查你的信息',U(MODULE_NAME.'/subscriberindex'));
		}
	}
	
	public function postMsgIndex(){
		$type = $_GET['type'];
		$id = $_GET['id'];
		
		$where['token'] = session('token');
		
		if($type=='group'){
			$where['groupid'] = $id;
			$model = M('subscribe_group')->where($where)->find();
		}else if($type=='personal'){
			$where['openid'] = $id;
			$model = M('subscriber')->where($where)->find();
		}else{
			$this->error('错误的请求',U(MODULE_NAME.'/subscriberindex'));
		}
		
		$this->assign('type', $type);
		$this->assign('model',$model);
		$this->assign('id',$id);
		
		$this->display();
	} 
	
	public function postMsg(){
		$type = $_POST['type'];
		$id = $_POST['oid'];
		$msg = $_POST['response'];
		
		if (strlen ( $msg ) == 0) {
			$this->error ( '发送内容不能为空', U ( MODULE_NAME . '/subscriberindex' ) );
		} else {
			if($type=='group'){
				$where['token'] = session('token');
				$where['groupid'] = $id;
				$model = M('subscriber')->where($where)->select();
				
				$suc = 0;
				$err = 0;
				
				foreach ($model as $user){
					$result = WechatAdvanceAPI::PostMsg ( array (
							'content' => urlencode ( $msg )
					), $user['openid'], 'text' );
					
					if($result){
						$suc++;
					}else {
						$err++;
					}
				}
				$this->success ( '发送完成，其中成功'.$suc.'个，失败'.$err.'个', U ( MODULE_NAME . '/subscriberindex') );
			}else if($type=='personal'){
				$result = WechatAdvanceAPI::PostMsg ( array (
						'content' => urlencode ( $msg )
				), $id, 'text' );
				
				if ($result === false) {
					$this->error ( '操作失败，请检查你的AppId和AppSecret，并确保回复的请求是在48小时内的', U ( MODULE_NAME . '/subscriberindex' ) );
				} else {
					$this->success ( '操作成功', U ( MODULE_NAME . '/subscriberindex' ) );
				}
				
			}else{
				$this->error('错误的请求',U(MODULE_NAME.'/subscriberindex'));
			}
		}
	}
	
}